﻿using System;
using System.Reflection;
using System.Text;
using System.IO;

namespace CommonTools.Storage
{
    public class Logs
    {
        static readonly string Path = System.Configuration.ConfigurationManager.AppSettings["system_logs_path"];

        public static bool SaveObject(object t, string level = "error")
        {
            var logTxt = new StringBuilder();
            logTxt.Append("{");
            PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            foreach (PropertyInfo item in properties)
            {
                string name = item.Name;
                object value = item.GetValue(t, null);
                logTxt.AppendFormat("[{0}:'{1}'],", name, value);
            }
            logTxt.Append("}");
            logTxt.AppendFormat("[LogTime:{0}]", DateTime.Now);
            return Save(logTxt.ToString(), level);
        }

        public static bool Save(string content, string level, bool nodate = false)
        {
            var sblog = new StringBuilder();
            sblog.AppendFormat(@"{0}\{1}", Path ?? Directory.GetCurrentDirectory(), DateTime.Now.ToString("yyyyMM"));
            string logPath = sblog.ToString();
            logPath = PathHandle(logPath, level);
            content = nodate ? string.Format("{0}", content) : string.Format("--{0}--:{1}", DateTime.Now, content);
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(logPath, true, Encoding.Default);
                sw.WriteLine(content);
                sw.Close();
                sw.Dispose();
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        private static string PathHandle(string logPath, string level)
        {
            if (!Directory.Exists(logPath)) Directory.CreateDirectory(logPath);
            logPath = string.Format("{0}/{1} - level({2}).log", logPath, DateTime.Now.Day, level);
            return logPath;
        }
    }
}
